<?php

session_start();

// include settings and functions
include "../conn/database.php";
include "functions.php";
include 'UUID.php';

// if the user submit the form
if(isset($_POST['submit'])) {
	// initialize errors values
	$errors=0;
	$errors_text = '';
	// cleanning the post data from hacking attempt
	$post_data = clean($_POST);
	
	// empty post data verification
	if(empty($_POST['addevent-step'])
	||empty($_POST['event_name']) || empty($_POST['event_titre'])
	|| empty($_POST['hh']) || empty($_POST['mn'])
	|| empty($_POST['adresse']) || empty($_POST['code'])
	|| empty($_POST['ville']) || empty($_POST['pays'])
	|| empty($_POST['voiture']) || empty($_POST['train']) || empty($_POST['avion'])) {
		$errors_text .= "Des champs sont vides";
		$errors++;
	}
		
	// time verification (is valid date)
	if(!check_time($post_data['hh'], $post_data['mn'])) {
		$errors_text .= "La date n'est pas valide";
		$errors++;
	}
	
	// if no errors we proceed
	if($errors == 0) {
		// data correction
		$wid = $_SESSION['wid'];
		$read_weddingdate = mysql_fetch_row(mysql_query("SELECT WEDDING_DATE FROM `T_WEDDINGS` WHERE WEDDING_ID ='".$wid."'"));
		$time = $read_weddingdate[0]." ".$post_data['hh'].":".$post_data['mn'];
		$index = $post_data['addevent-step'];
		
		// generating the event ID
		$eid = UUID::v5('1546058f-5a25-4334-85ae-e68f2a44bbaf', generate_guid(6));
		
		$insert_sql = "
			INSERT INTO `T_EVENTS`
			(`EVENT_ID`, `WEDDING_ID`, `START_TIME`, `INDEX`, `TITLE`, `DESCRIPTION`, `PHOTO_ID`, `DATE`,
			`CAR_ACCESS_DESC`, `PLANE_ACCESS_DESC`, `TRAIN_ACCESS_DESC`, `STREET`, `POSTAL_CODE`, `CITY`, `COUNTRY`, `EVENT_TYPE_ID`)
			VALUES
			('".$eid."','".$wid."','".$time."','".$index."','".$post_data['event_titre']."','null','','".$read_weddingdate[0]."',
			'".$post_data['voiture']."','".$post_data['avion']."','".$post_data['train']."','".$post_data['adresse']."',
			'".$post_data['code']."','".$post_data['ville']."','".$post_data['pays']."','".$post_data['event_name']."')"
		;
		
		if(!mysql_query($insert_sql)) {
			$errors_text .= mysql_error()."<br />";
			$errors++;
		} else {
			$_SESSION['eid-'.$post_data['addevent-step']] = $eid;
			if($post_data['addevent-step'] == 6)
				$tagURL = "grandjour.php?event=6";
			else 
				$tagURL = "grandjour.php?event=".($post_data['addevent-step']+1);
		}
	}
	if($errors == 0) {
		$arr['success'] = "1"; 
        $arr['msg'] = 'Vos informations ont bien été enregistrées.';
		$arr['url'] = $tagURL;
	} else {
		$arr['success'] = "0"; 
        $arr['msg'] = $errors_text;
	}
	echo json_encode($arr);
}
?>